package absolute_zero.com.urbox;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import absolute_zero.com.urbox.transmition.Server;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class urbox_receive extends Activity {
    
/********************* INSTANCE VARIABLES **********************************/
	
	//Receive Screen Elements
	Button accept;
	Button reject;
	TextView contactInfo;
	TextView fileInfo;
	
	//Transfer Screen Elements
	TextView transferInfo;
	ProgressBar progress;
	Button cancel;

	//Variables
	String pkgNum;
	private String file_name;
	private ImageView image;
	private String message;
	private String address;
	private NotificationManager mNotificationManager;
	
/******************* INITIALIZING METHODS ***********************************/
	
	/** Called when screen is turned **/
    @Override
    public void onConfigurationChanged(Configuration newConfig){
    	super.onConfigurationChanged(newConfig);
    }
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.receive);
        
        //cancel screen 
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  
        urbox_receive.this.mNotificationManager.cancel(1); 

        
        Bundle info = getIntent().getExtras();
        //Get info from bundle
        file_name = info.getString("file_name");
        message = info.getString("message");
        address = info.getString("address");
        
        //Setup Screen Elements
        contactInfo = (TextView)this.findViewById(R.id.transfer_info);
    	fileInfo = (TextView)this.findViewById(R.id.file_detail_info);
    	accept = (Button)this.findViewById(R.id.Accept_Receive);
    	reject = (Button)this.findViewById(R.id.Reject_Receive);
    	image = (ImageView)this.findViewById(R.id.icon);
    	accept.setVisibility(0);
    	reject.setVisibility(0);
    	//progress = (ProgressBar)this.findViewById(R.id.receiveBar);
    	
    	if (checkEndsWithInStringArray(file_name, getResources()
    			.getStringArray(R.array.fileEndingImage))) {
    		image.setImageDrawable(getResources().getDrawable(R.drawable.image));
    	} else if (checkEndsWithInStringArray(file_name,
    			getResources().getStringArray(R.array.fileEndingWebText))) {
    		image.setImageDrawable(getResources().getDrawable(R.drawable.webtext));
    				//.getDrawable()));
    	} else if (checkEndsWithInStringArray(file_name,
    			getResources().getStringArray(R.array.fileEndingPackage))) {
    		image.setImageDrawable(getResources().getDrawable(R.drawable.archive));
    	} else if (checkEndsWithInStringArray(file_name,
    			getResources().getStringArray(R.array.fileEndingAudio))) {
    		image.setImageDrawable(getResources().getDrawable(R.drawable.audio));
    				//.getDrawable()));
    	} else if (checkEndsWithInStringArray(file_name,
    			getResources().getStringArray(R.array.fileEndingText))) {
    		image.setImageDrawable(getResources().getDrawable(R.drawable.text));
    	} else if (checkEndsWithInStringArray(file_name,
    			getResources().getStringArray(R.array.fileEndingVideo))) {
    		image.setImageDrawable(getResources().getDrawable(R.drawable.video));
    	} else {
    		image.setImageDrawable(getResources().getDrawable(R.drawable.blank_file));
    	}
    	
    	//Gather and display contact info and file info
        receiveTransferInfo();
       
        //Add Button listeners
        accept.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                setContentView(R.layout.transfer);
                transferProcess();
            }
        });
        reject.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                finish();
                
            }
        });
    }
    
/****************** SELF-MADE METHODS **************************************/
    // Checks whether checkItsEnd ends with one of the Strings from fileEndings 
    private boolean checkEndsWithInStringArray(String checkItsEnd, String[] fileEndings){
         for(String aEnd : fileEndings){
              if(checkItsEnd.endsWith(aEnd))
                   return true;
         }
         return false;
    }
    
    /** Reads transfer info and displays to screen. */
    public void receiveTransferInfo() {
    	//Read from server into variables
    	//TODO: replace with name
    	String contactName = "John Doe";
    	String fileName = file_name;
    	
    	contactInfo.setText("\n" + contactName + "\nwants to send you a file.\n");
    	fileInfo.setText("\n" + fileName + "\n");    	
    	
    }
    
    private void sendIPData(Context context, Intent intent) {
		// Get connectivity status
		
		String IP = getLocalIpAddress();

		Log.d("Sending IP address", IP);
		SmsManager mng = SmsManager.getDefault();
		

		Log.d("Retrieving from whence this msg came", address);
		
		try {
			mng.sendTextMessage(address, null, "UrBox_reponse" + IP, null, null);
			Log.d("Sent IP", IP);
		} catch (Exception e) {
			Log.e("SmsIntent", "SendException", e);
		}
	}
    
    public String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
			//Log.e(S.TAG, ex.toString());
		}
		return null;
	}
    
    /** The functions for the transfer screen. */
    public void transferProcess() {
    	//Setup Screen Elements
    	transferInfo = (TextView)this.findViewById(R.id.transferring_details);
    	cancel = (Button)this.findViewById(R.id.ok_button);
    	progress = (ProgressBar)this.findViewById(R.id.receiveBar);
    	progress.setVisibility(0);
    	progress.setIndeterminate(true);
    	//Redisplay Transfer Info
    	transferInfo.setText(fileInfo.getText().toString());
		//Start Server
    	
    	Thread server = new Server(progress);
    	server.start();
    	Log.d("new server started", server.getName());
    	sendIPData(this, this.getIntent());
    	//Add Button listeners
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	cancelTransferring();
            	finish();
            }
        });
    }
    
    
    /** The function for canceling a transfer. */
    public void cancelTransferring() {
    	//TODO: Write the function to end the transfer
    	
    }
    
}